package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口 包括文件上传接口等
 */
@RestController
@RequestMapping("admin/common")
@Api(tags="通用接口")
@Slf4j
public class CommonController {

    //依赖注入阿里云工具类
    @Autowired
    private AliOssUtil aliOssUtil;
    @ApiOperation("文件上传接口")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {   //接收前端发来的文件
        log.info("{}文件上传中————————————",file);

        //存储到阿里云上
        try{

            //为防止重复等问题，使用uuid拼接图片名
            String originalFilename = file.getOriginalFilename();

            //截取文件格式后缀
            String suf = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String newName = UUID.randomUUID().toString()+suf;

            String filePath = aliOssUtil.upload(file.getBytes(), newName);//调用工具类接口方法 返回文件路径
            return Result.success(filePath);
        }catch(Exception e){
            e.printStackTrace();
            log.info("文件上传失败————————————————————————");
        }

//        return Result.error("文件上传失败");
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

}
